﻿
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of our gameRoom. Knockout uses to update UI.
function gameRoomViewModel(g, h) {
    var self = this;
    // Need to have references to hub and group for communication.
    var group = g;
    var masterHub = h;

    self.slots = ko.observableArray([]);
    self.gameRoomName = ko.observable("");
    self.gameRoomState = ko.observable("");
    self.gameRoomID = 0;
    self.currentUserID = 0;
    self.currentUserName = null;
    self.hostUserID = 0;
    self.minPlayers = 0;
    self.playableCPU = false;
    self.slotNumber = 0;

    self.hasMinPlayers = ko.computed(function () {
        // Filter slots to only return ready.
        var readySlots = _.filter(self.slots(), function (s) { return s.ready; });
        return readySlots.length >= self.minPlayers;
    });

    self.players = ko.computed(function () {
        // Filter slots to only return occupied.
        var occupiedSlots = _.filter(self.slots(), function (s) { return s.occupied; });
        return occupiedSlots;
    });

    self.changeName = function () {
        var name = prompt("Nýtt nafn á leikinn: ", "");
        masterHub.server.updateName(group, self.gameRoomID, name);
    }
    self.playerReady = function (s) {
        masterHub.server.updateSlot(group, JSON.stringify(s), self.gameRoomID);
    }
    self.startGame = function () {
        // TODO: what happens to those that are already connected but not ready?
        // Remove not ready players.
        var readyPlayers = _.filter(self.slots(), function (s) { return s.ready; });
        masterHub.server.updateSlots(group, JSON.stringify(readyPlayers), self.gameRoomID);
        // And update game state.
        masterHub.server.startGame(group, self.gameRoomID);
    }

    self.playComputer = function (slot) {
        slot.ready = true;
        slot.occupied = true;
        slot.userName = "CPU";
        slot.isCPU = true;
        slot.userImage = "/Images/CPU.jpg";
        // Notify others.
        masterHub.server.updateSlot(group, JSON.stringify(slot), self.gameRoomID);
    }

    // Marks the playerMenu class as a JqueryUI menu.
    $(".playerMenu").menu();

    // Shows the player menu when player hovers over an empty slot.
    onMouseOver = function (data, event) {
        $(event.target).children(".playerMenu").show();
    }

    // Hides the player menu when player hovers from an empty slot.
    onMouseLeave = function (data, event) {
        var $el = $(event.currentTarget).children(".playerMenu").hide();
    }

    /*var myHub = $.connection.masterHub;

    myHub.client.acceptInvite = function (roomID, playerName) {
        gameRoomInvite = roomID;
        $("#userInvited").text(playerName);
        // Add the message to the page. 
        $("#invitationRecieved").dialog("open");
    };*/
}
